#!/usr/bin/env python3
# Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# hacmp-aix
# <<<aix_hacmp_services>>>
# Status of the RSCT subsystems used by PowerHA SystemMirror:
# Subsystem         Group            PID          Status
#  cthags           cthags           8257694      active
#  ctrmc            rsct             7995636      active
#
# Status of the PowerHA SystemMirror subsystems:
# Subsystem         Group            PID          Status
#  clstrmgrES       cluster          9109590      active
#  clevmgrdES       cluster          29098102     active
#
# Status of the CAA subsystems:
# Subsystem         Group            PID          Status
#  clcomd           caa              6619358      active
#  clconfd          caa              10944716     active
#
# Details of PowerHA SystemMirror cluster manager:
# Current state: ST_STABLE
# sccsid = "@(#)36 1.135.1.118 src/43haes/usr/sbin/cluster/hacmprd/main.C,hacmp.pe,61haes_r713,1343A_hacmp713 10/21/"
# build = "Oct 27 2014 16:03:01 1433C_hacmp713"
# i_local_nodeid 1, i_local_siteid -1, my_handle 1
# ml_idx[1]=1 ml_idx[2]=0
# There are 0 events on the Ibcast queue
# There are 0 events on the RM Ibcast queue
# CLversion: 15
# local node vrmf is 7132
# cluster fix level is "2"
# The following timer(s) are currently active:
# Current DNP values
# DNP Values for NodeId - 2  NodeName - pasv0449
#     PgSpFree = 6280459  PvPctBusy = 0  PctTotalTimeIdle = 40.060893
# DNP Values for NodeId - 1  NodeName - pasv0450
#     PgSpFree = 6276175  PvPctBusy = 0  PctTotalTimeIdle = 80.135962
# CAA Cluster Capabilities
# CAA Cluster services are active
# There are 4 capabilities
# Capability 0
#   id: 3  version: 1  flag: 1
#   Hostname Change capability is defined and globally available
# Capability 1
#   id: 2  version: 1  flag: 1
#   Unicast capability is defined and globally available
# Capability 2
#   id: 0  version: 1  flag: 1
#   IPV6 capability is defined and globally available
# Capability 3
#   id: 1  version: 1  flag: 1
#   Site capability is defined and globally available
# trcOn 0, kTraceOn 0, stopTraceOnExit 0, cdNodeOn 0
# Last event run was DA_RES_CO     on node 2

# parsed = {
#  u'CAA': [(u'clcomd', u'caa', u'6619358', u'active'),
#           (u'clconfd', u'caa', u'10944716', u'active')],
#  u'PowerHA SystemMirror': [(u'clstrmgrES', u'cluster', u'9109590', u'active'),
#                            (u'clevmgrdES', u'cluster', u'29098102', u'active')],
#  u'RSCT': [(u'cthags', u'cthags', u'8257694', u'active'),
#            (u'ctrmc', u'rsct', u'7995636', u'active')],
# }


# mypy: disable-error-code="var-annotated"

from typing import Any

from cmk.agent_based.v2 import (
    AgentSection,
    CheckPlugin,
    CheckResult,
    DiscoveryResult,
    Result,
    Service,
    State,
)


def parse_aix_hacmp_services(string_table):
    parsed = {}
    inst = None
    for line in string_table:
        if line[0] == "Details":
            inst = None

        elif line[0] == "Status":
            subsystem_ty_name = line[3]
            if subsystem_ty_name == "PowerHA":
                subsystem_ty_name += " %s" % line[4]
            inst = parsed.setdefault(subsystem_ty_name, [])

        elif line[0] == "Subsystem":
            # header line
            continue

        elif inst is not None and len(line) in [3, 4]:
            # Not all lines contain PID:
            # clcomd   caa  7537142  active
            # clconfd  caa           inoperative
            inst.append((line[0], line[-1]))

    return parsed


def check_aix_hacmp_services(item: str, section: Any) -> CheckResult:
    if not (data := section.get(item)):
        return

    yield from (
        Result(
            state=State.OK if status == "active" else State.CRIT,
            summary=f"Subsystem: {subsytem_name}, Status: {status}",
        )
        for subsytem_name, status in data
    )


def discover_aix_hacmp_services(section: Any) -> DiscoveryResult:
    yield from (Service(item=item) for item in section)


agent_section_aix_hacmp_services = AgentSection(
    name="aix_hacmp_services", parse_function=parse_aix_hacmp_services
)
check_plugin_aix_hacmp_services = CheckPlugin(
    name="aix_hacmp_services",
    service_name="HACMP Service %s",
    discovery_function=discover_aix_hacmp_services,
    check_function=check_aix_hacmp_services,
)
